package com.qingpeng.pay.service;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.support.annotation.RequiresApi;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.qingpeng.pay.R;
import com.qingpeng.pay.api.Host;
import com.qingpeng.pay.api.RedBag;
import com.qingpeng.pay.okhttp.RetrofitCreateHelper;
import com.qingpeng.pay.utils.APP;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class NLService extends NotificationListenerService implements AsyncResponse, IDoPost {
    private String TAG = "NLService";
    private String posturl = null;
    private Timer mTimer;
    public static final int NOTICE_ID = 1;
    private MediaPlayer bgmediaPlayer;

    @Override
    public void onCreate() {
        super.onCreate();
        mTimer = new Timer();
    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        isShow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createNotificationChannel();
            if (bgmediaPlayer == null) {
                bgmediaPlayer = MediaPlayer.create(this, R.raw.wusheng);
                bgmediaPlayer.setLooping(true);
                bgmediaPlayer.start();
            }
        } else {
            Notification.Builder builder = new Notification.Builder(this);
            builder.setSmallIcon(R.mipmap.ic_log);
            builder.setContentTitle("乐刷");
            builder.setContentText("正在接单请不要关闭应用");
            startForeground(NOTICE_ID, builder.build());
        }
        return START_STICKY;
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void createNotificationChannel() {
        NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        // 通知渠道的id
        String id = "my_channel_01";
        // 用户可以看到的通知渠道的名字.
        CharSequence name = "乐刷";
//         用户可以看到的通知渠道的描述
        String description = "正在接单请不要关闭应用";
        int importance = NotificationManager.IMPORTANCE_HIGH;
        NotificationChannel mChannel = new NotificationChannel(id, name, importance);
//         配置通知渠道的属性
        mChannel.setDescription(description);
//         最后在notificationmanager中创建该通知渠道 //
        mNotificationManager.createNotificationChannel(mChannel);

        // 为该通知设置一个id
        int notifyID = 1;
        // 通知渠道的id
        String CHANNEL_ID = "my_channel_01";
        // Create a notification and set the notification channel.
        Notification notification = new Notification.Builder(this)
                .setContentTitle("乐刷").setContentText("正在接单请不要关闭应用")
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setChannelId(CHANNEL_ID)
                .build();
        startForeground(notifyID, notification);
    }

    private void isShow() {
        if (APP.is) {
            Call<ResponseBody> postceshi = RetrofitCreateHelper.createApi(RedBag.class, Host.HOST).getmessage();
            postceshi.enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    TimerTask task = new TimerTask() {
                        @Override
                        public void run() {
                            /**
                             *要执行的操作
                             */
                            isShow();
                        }
                    };
                    mTimer.schedule(task, 3000);//3秒后执行TimeTask的run方法

                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    TimerTask task = new TimerTask() {
                        @Override
                        public void run() {
                            /**
                             *要执行的操作
                             */
                            isShow();
                        }
                    };
                    mTimer.schedule(task, 3000);//3秒后执行TimeTask的run方法
                }
            });
        }
    }

    private String getPostUrl() {
        SharedPreferences sp = getSharedPreferences("url", 0);
        this.posturl = sp.getString("posturl", "");
        APP.uid = sp.getString("id", "");
        if (posturl == null)
            return null;
        else
            return posturl;
    }


    @Override
    public void onNotificationPosted(StatusBarNotification sbn) {
        //        super.onNotificationPosted(sbn);
        //这里只是获取了包名和通知提示信息，其他数据可根据需求取，注意空指针就行
        Log.d(TAG, "接受到通知消息");
        Notification notification = sbn.getNotification();
        String pkg = sbn.getPackageName();

        if (notification == null) {
            return;
        }

        Bundle extras = notification.extras;
        Log.d(TAG, extras.toString());
        if (extras == null)
            return;

        Log.d(TAG, "-----------------");

        //mipush
        if ("com.xiaomi.xmsf".equals(pkg)) {
            if (getNotiTitle(extras).contains("支付宝")) {
                //printNotify(getNotitime(notification),getNotiTitle(extras),getNotiContent(extras));
                new MipushNotificationHandle("com.xiaomi.xmsf", notification, this).handleNotification();

            }

        }
        //支付宝
        if ("com.eg.android.AlipayGphone".equals(pkg)) {
            new AlipayNotificationHandle("com.eg.android.AlipayGphone", notification, this).handleNotification();

        }
        //应用管理GCM代收
        if ("android".equals(pkg)) {

            new XposedmoduleNotificationHandle("github.tornaco.xposedmoduletest", notification, this).handleNotification();
        }
        //微信
        if ("com.tencent.mm".equals(pkg)) {

            new WechatNotificationHandle("com.tencent.mm", notification, this).handleNotification();

        }

        Log.d(TAG, "这是检测之外的其它通知");
        Log.d(TAG, "包名是" + pkg);
        printNotify(getNotitime(notification), getNotiTitle(extras), getNotiContent(extras));

        Log.d(TAG, "**********************");


    }

    @Override
    public void onNotificationRemoved(StatusBarNotification sbn) {
        if (Build.VERSION.SDK_INT > 19)
            super.onNotificationRemoved(sbn);
    }

    private void sendBroadcast(String msg) {
        Intent intent = new Intent(getPackageName());
        intent.putExtra("text", msg);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intent);
    }

    private String getNotitime(Notification notification) {

        long when = notification.when;
        Date date = new Date(when);
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm");
        String notitime = format.format(date);
        return notitime;

    }

    private String getNotiTitle(Bundle extras) {
        String title = null;
        // 获取通知标题
        title = extras.getString(Notification.EXTRA_TITLE, "");
        return title;
    }

    private String getNotiContent(Bundle extras) {
        String content = null;
        // 获取通知内容
        content = extras.getString(Notification.EXTRA_TEXT, "");
        return content;
    }

    private void printNotify(String notitime, String title, String content) {
        Log.d(TAG, notitime);
        Log.d(TAG, title);
        Log.d(TAG, content);
    }


    public void doPost(Map<String, String> params) {
        PreferenceUtil preference = new PreferenceUtil(getBaseContext());
        Map<String, String> tmpmap = params;
        Map<String, String> postmap = null;
        Log.d(TAG, "开始准备进行post");
        PostTask mtask = new PostTask();
        mtask.setOnAsyncResponse(this);
        tmpmap.put("encrypt", "0");
        tmpmap.put("url", this.posturl);
        String deviceid = preference.getDeviceid();
        tmpmap.put("deviceid", deviceid != "" ? deviceid : DeviceInfoUtil.getUniquePsuedoID());

        if (postmap != null)
            mtask.execute(postmap);
        else
            mtask.execute(tmpmap);
    }


    @Override
    public void onDataReceivedSuccess(String returnstr) {
        Log.d(TAG, "Post Receive-returned post string");
        Log.d(TAG, returnstr);


    }

    @Override
    public void onDataReceivedFailed() {
        // TODO Auto-generated method stub
        Log.d(TAG, "Post Receive-post error");

    }

    @Override
    public void onDestroy() {
        if (Context.NOTIFICATION_SERVICE != null) {
            String ns = Context.NOTIFICATION_SERVICE;
            NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);
            nMgr.cancel(NOTICE_ID);
        }
        stopForeground(true);
        if (bgmediaPlayer != null) {
            bgmediaPlayer.release();
        }
        stopSelf();
        super.onDestroy();
    }
}
